package com.cyrus.vueboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyrus.vueboot.mapper.dpt.DepartmentMapper;
import com.cyrus.vueboot.mapper.dpt.DepartmentUserMapper;
import com.cyrus.vueboot.pojo.dpt.Department;
import com.cyrus.vueboot.pojo.dpt.DepartmentUser;
import com.cyrus.vueboot.service.DepartmentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/25
 */
@Service
public class DepartmentUserServiceImpl extends ServiceImpl<DepartmentUserMapper, DepartmentUser> implements DepartmentUserService {
    @Autowired
    DepartmentUserMapper departmentUserMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    public IPage search(Integer page, Integer size, String key) {
        IPage<DepartmentUser> page1 = departmentUserMapper.selectPage(new Page<DepartmentUser>(page, size), new QueryWrapper<DepartmentUser>().lambda().like(DepartmentUser::getUsername, key).eq(DepartmentUser::getIsDelete, 0));
        return page1;
    }

    @Override
    public void delDepartmentUsers(Long[] ids) {
        List<Department> departments = departmentMapper.selectList(new QueryWrapper<Department>().lambda().eq(Department::getIsDelete, 0));
        ArrayList<String> dptManagers = new ArrayList();
        for (Department department : departments) {
            String dptManager = department.getDptManager();
            dptManagers.add(dptManager);
        }
        for (Long id : ids) {
            if (!dptManagers.contains(departmentUserMapper.selectById(id).getUsername())) {
                update(new UpdateWrapper<DepartmentUser>().lambda().set(DepartmentUser::getIsDelete, 1).eq(DepartmentUser::getId, id));
            } else {
                throw new RuntimeException("当前删除用户中存在部门负责人！删除失败");
            }

        }
    }
}
